package com.mender.trade.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mender.api.client.UserClient;
import com.mender.common.constant.MessageConstant;
import com.mender.common.context.BaseContext;
import com.mender.common.exception.AddressBookBusinessException;
import com.mender.common.exception.OrderBusinessException;
import com.mender.common.result.PageResult;
import com.mender.common.result.Result;
import com.mender.common.utils.HttpClientUtil;
import com.mender.common.utils.WeChatPayUtil;
import com.mender.domain.dto.GoodsSalesDTO;
import com.mender.domain.po.AddressBook;
import com.mender.domain.po.User;
import com.mender.trade.domain.dto.*;
import com.mender.trade.domain.po.OrderDetail;
import com.mender.domain.po.Orders;
import com.mender.trade.domain.po.ShoppingCart;
import com.mender.trade.domain.vo.OrderPaymentVO;
import com.mender.trade.domain.vo.OrderStatisticsVO;
import com.mender.trade.domain.vo.OrderSubmitVO;
import com.mender.trade.domain.vo.OrderVO;
import com.mender.trade.mapper.OrderDetailMapper;
import com.mender.trade.mapper.OrderMapper;
import com.mender.trade.mapper.ShoppingCartMapper;
import com.mender.trade.service.OrderService;
import com.mender.trade.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private UserClient userClient;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
//        判断地址和购物车是否为空
        Result<AddressBook> ResultbyId = userClient.getAddressBookById(ordersSubmitDTO.getAddressBookId());
        AddressBook byId=ResultbyId.getData();
        if (byId == null)
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);

//        判断用户地址是否超出配送范围
        checkOutOfRange(byId.getCityName()+byId.getDistrictName()+byId.getDetail());

//        查询当前用户的购物车数据
        Long currentId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(currentId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list == null || list.size() == 0)
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        //        生成订单
        String number = String.valueOf(System.currentTimeMillis());//订单号
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setAddress(byId.getDetail());
        orders.setUserId(currentId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(number);
        orders.setPhone(byId.getPhone());
        orders.setConsignee(byId.getConsignee());
        orderMapper.insert(orders);

//        向订单明细表插入n个数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        list.forEach(shoppingCart1 -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart1, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });
        orderDetailMapper.insertBatch(orderDetailList);

//        清空当前购物车
        shoppingCartMapper.delete(shoppingCart);


        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();

//        TODO paySuccess模拟用户付款成功
        //业务处理，修改订单状态、来单提醒
        paySuccess(number);
        return orderSubmitVO;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        Result<User> resultUser = userClient.getUserById(userId);
        User user = resultUser.getData();

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

//        通过websocket向客户端推送消息,
        Map map = new HashMap();
        map.put("type",1); //1来单提醒,2客户催单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号:"+outTradeNo);
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);//推送消息
    }

    /**
     * 分页查询历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult getPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();
        page.forEach(orders -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            List<OrderDetail> list = orderDetailMapper.getOrderDishes(orders.getId());
            orderVO.setOrderDetailList(list);
            orderVOList.add(orderVO);
        });

        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * 根据id查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderDetail(Long id) {
        Orders orders = orderMapper.getByIdAndUserId(id, BaseContext.getCurrentId());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        List<OrderDetail> list = orderDetailMapper.getOrderDishes(id);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) throws Exception {
        Long currentId = BaseContext.getCurrentId();
        Orders byIdAndUserId = orderMapper.getByIdAndUserId(id, currentId);

//        校验订单是否存在
        if (byIdAndUserId == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //        校验订单状态,待付款和待接单时可直接取消
        if (byIdAndUserId.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
//        订单处于待接单时需要进行退款
        if (byIdAndUserId.getPayStatus() == Orders.TO_BE_CONFIRMED) {
            weChatPayUtil.refund(
                    byIdAndUserId.getNumber(), //商户订单号
                    byIdAndUserId.getNumber(), //商户退款单号
                    new BigDecimal(0.01), //退款金额，单位 元
                    new BigDecimal(0.01) //原订单金额
            );
            orders.setPayStatus(Orders.REFUND);
        }
        orders = Orders.builder()
                .id(id)
                .userId(currentId)
                .status(Orders.CANCELLED)
                .cancelReason("用户取消")
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
//        获取当前id相关的菜品信息
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(id);
        List<OrderDetail> orderDetails = orderDetailMapper.select(orderDetail);

        //将菜品信息添加到购物车
        orderDetails.forEach(orderDetail1 -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(BaseContext.getCurrentId());
            BeanUtils.copyProperties(orderDetail1, shoppingCart);
            shoppingCartMapper.insert(shoppingCart);
        });

    }

    /**
     * 管理端订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> orderVOList = new ArrayList<>();
        List<Orders> ordersList = page.getResult();
        ordersList.forEach(orders -> {
           OrderVO orderVO = new OrderVO();
           BeanUtils.copyProperties(orders, orderVO);
           orderVO.setOrderDishes(getOrderDishesStr(orders));
           orderVOList.add(orderVO);
        });
        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * 各个状态的订单数统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
//        待接单
        orderStatisticsVO.setToBeConfirmed(orderMapper.countByStatus(Orders.TO_BE_CONFIRMED));
//        已接单
        orderStatisticsVO.setConfirmed(orderMapper.countByStatus(Orders.CONFIRMED));
        //        派送中
        orderStatisticsVO.setDeliveryInProgress(orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS));
        return orderStatisticsVO;
    }

    /**
     * 查看订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        Orders orders = orderMapper.getByIdAndUserId(id,null);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailMapper.getOrderDishes(orders.getId()));
        return orderVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
//        改变当前id的订单状态
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void refuse(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
//        校验订单是否存在
        Long id = ordersRejectionDTO.getId();
        Orders byIdAndUserId = orderMapper.getByIdAndUserId(id, null);
        if (byIdAndUserId == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //        校验订单状态,待接单时可以拒绝
        if (byIdAndUserId.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //        如果订单已经支付，则进行退款操作
        if (byIdAndUserId.getPayStatus() == Orders.PAID){
            weChatPayUtil.refund(
                    byIdAndUserId.getNumber(), //商户订单号
                    byIdAndUserId.getNumber(), //商户退款单号
                    new BigDecimal(0.01), //退款金额，单位 元
                    new BigDecimal(0.01) //原订单金额
            );
        }
        //        改变当前id的订单状态
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 商家取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
//        若用于已支付,需要进行退款
        Orders byIdAndUserId = orderMapper.getByIdAndUserId(ordersCancelDTO.getId(), null);
        if (byIdAndUserId.getPayStatus() == Orders.PAID){
            weChatPayUtil.refund(
                    byIdAndUserId.getNumber(), //商户订单号
                    byIdAndUserId.getNumber(), //商户退款单号
                    new BigDecimal(0.01), //退款金额，单位 元
                    new BigDecimal(0.01) //原订单金额
            );
        }
        Orders build = Orders.builder()
                .id(ordersCancelDTO.getId())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(build);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
//        判断当前订单是否为派送中
        Orders byIdAndUserId = orderMapper.getByIdAndUserId(id, null);
        if (byIdAndUserId.getStatus() != Orders.CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
//        更新订单状态
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
//        派送中的订单可以执行完成订单操作
        Orders byIdAndUserId = orderMapper.getByIdAndUserId(id, null);
        if (byIdAndUserId == null||byIdAndUserId.getStatus() != Orders.DELIVERY_IN_PROGRESS) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 客户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders byIdAndUserId = orderMapper.getByIdAndUserId(id, null);
//        校验订单是否存在
        if (byIdAndUserId == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map = new HashMap<>();
        map.put("message",2);//1来单提醒,2催单
        map.put("orderId",id);
        map.put("content","订单号"+byIdAndUserId.getNumber());
        String json = JSON.toJSONString(map);
//        推送消息
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 查询订单总数
     * @param params
     * @return
     */
    @Override
    public Integer countOrderByMap(Map<String, Object> params) {
        return orderMapper.countByMap(params);
    }

    /**
     * 营业额统计
     */
    @Override
    public Double sumByMap(Map<String, Object> params) {
        return orderMapper.sumByMap(params);
    }

    /**
     * 查询所有已完成订单数据（一次性查出范围内所有订单）
     * getCompletedOrdersByTime
     */
    @Override
    public List<Orders> getCompletedOrdersByTime(LocalDateTime beginTime, LocalDateTime endTime,Integer status) {
        return orderMapper.getCompletedOrdersByTime(beginTime, endTime, status);
    }

    /**
     * 根据指定时间查询符合条件的菜品
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public List<GoodsSalesDTO> getOrderDetailTop10(LocalDateTime beginTime, LocalDateTime endTime) {
        return orderDetailMapper.getTop10(beginTime, endTime);
    }

    /**
     * 根据订单id查询菜品信息字符串
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders){
        List<OrderDetail> orderDetails = orderDetailMapper.getOrderDishes(orders.getId());
        StringBuilder sb = new StringBuilder();
        orderDetails.forEach(orderDetail -> {
            sb.append(orderDetail.getName());
            sb.append("*");
            sb.append(orderDetail.getNumber());
            sb.append(";");
        });
        return sb.toString();
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        // 如果 Redis 中没有缓存，则请求接口并写入缓存
        String shopCoordinate = (String) redisTemplate.opsForValue().get(shopAddress);
        if (shopCoordinate == null){
            //获取店铺的经纬度坐标
            shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
//            将数据存入缓存
            redisTemplate.opsForValue().set(shopAddress,shopCoordinate);
            System.out.println("缓存没有数据,请求api");
        }
        System.out.println("缓存有数据,直接使用"+shopCoordinate);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }
        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }
}
